package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.mapper.CourseMapper;
import com.demo.mapper.StudentCourseMapper;
import com.demo.mapper.StudentMapper;
import com.demo.pojo.entity.Course;
import com.demo.pojo.entity.Student;
import com.demo.pojo.entity.StudentCourse;
import com.demo.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 成绩管理服务实现类
 */
@Service
public class GradeServiceImpl implements GradeService {
    
    @Autowired
    private StudentCourseMapper studentCourseMapper;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Override
    @Transactional
    public boolean submitGrade(Long studentCourseId, BigDecimal usualGrade, BigDecimal examGrade, String remark) {
        try {
            StudentCourse studentCourse = studentCourseMapper.selectById(studentCourseId);
            if (studentCourse == null) {
                throw new RuntimeException("未找到该选课记录");
            }
            
            // 设置平时成绩和考试成绩
            studentCourse.setUsualGrade(usualGrade);
            studentCourse.setExamGrade(examGrade);
            
            // 计算总成绩和等级
            Map<String, Object> gradeResult = calculateFinalGrade(usualGrade, examGrade);
            studentCourse.setFinalGrade((BigDecimal) gradeResult.get("finalGrade"));
            studentCourse.setGradeLevel((String) gradeResult.get("gradeLevel"));
            
            // 设置备注
            if (remark != null && !remark.isEmpty()) {
                studentCourse.setRemark(remark);
            }
            
            // 更新状态为已完成
            studentCourse.setStatus("COMPLETED");
            studentCourse.setUpdateTime(new Date());
            
            return studentCourseMapper.updateById(studentCourse) > 0;
        } catch (Exception e) {
            throw new RuntimeException("提交成绩失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public int batchSubmitGrades(List<Map<String, Object>> grades) {
        int successCount = 0;
        for (Map<String, Object> gradeData : grades) {
            try {
                Long studentCourseId = Long.valueOf(gradeData.get("studentCourseId").toString());
                BigDecimal usualGrade = gradeData.get("usualGrade") != null ? 
                    new BigDecimal(gradeData.get("usualGrade").toString()) : null;
                BigDecimal examGrade = gradeData.get("examGrade") != null ? 
                    new BigDecimal(gradeData.get("examGrade").toString()) : null;
                String remark = gradeData.get("remark") != null ? 
                    gradeData.get("remark").toString() : null;
                
                if (submitGrade(studentCourseId, usualGrade, examGrade, remark)) {
                    successCount++;
                }
            } catch (Exception e) {
                // 继续处理下一条记录
                continue;
            }
        }
        return successCount;
    }
    
    @Override
    public List<Map<String, Object>> getCourseGrades(Long courseId, String semester) {
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId)
                   .in("status", Arrays.asList("SELECTED", "COMPLETED"));
        
        if (semester != null && !semester.isEmpty()) {
            queryWrapper.eq("semester", semester);
        }
        
        List<StudentCourse> studentCourses = studentCourseMapper.selectList(queryWrapper);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (StudentCourse sc : studentCourses) {
            Student student = studentMapper.selectById(sc.getStudentId());
            Course course = courseMapper.selectById(sc.getCourseId());
            
            if (student != null && course != null) {
                Map<String, Object> gradeInfo = new HashMap<>();
                
                // 学生选课记录ID
                gradeInfo.put("studentCourseId", sc.getId());
                
                // 学生信息
                gradeInfo.put("studentId", student.getStudentId());
                gradeInfo.put("stuNo", student.getStuNo());
                gradeInfo.put("stuName", student.getStuName());
                
                // 课程信息
                gradeInfo.put("courseId", course.getCourseId());
                gradeInfo.put("courseNo", course.getCourseNo());
                gradeInfo.put("courseName", course.getCourseName());
                gradeInfo.put("credit", course.getCredit());
                
                // 成绩信息
                gradeInfo.put("semester", sc.getSemester());
                gradeInfo.put("usualGrade", sc.getUsualGrade());
                gradeInfo.put("examGrade", sc.getExamGrade());
                gradeInfo.put("finalGrade", sc.getFinalGrade());
                gradeInfo.put("gradeLevel", sc.getGradeLevel());
                gradeInfo.put("status", sc.getStatus());
                gradeInfo.put("remark", sc.getRemark());
                gradeInfo.put("updateTime", sc.getUpdateTime());
                
                result.add(gradeInfo);
            }
        }
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getTeacherCourseGrades(Long teacherId, String semester) {
        // 查询教师负责的课程
        QueryWrapper<Course> courseWrapper = new QueryWrapper<>();
        courseWrapper.eq("teacher_id", teacherId);
        List<Course> courses = courseMapper.selectList(courseWrapper);
        
        List<Map<String, Object>> allGrades = new ArrayList<>();
        for (Course course : courses) {
            List<Map<String, Object>> courseGrades = getCourseGrades(course.getCourseId(), semester);
            allGrades.addAll(courseGrades);
        }
        
        return allGrades;
    }
    
    @Override
    @Transactional
    public boolean updateGrade(Long studentCourseId, BigDecimal usualGrade, BigDecimal examGrade, String remark) {
        return submitGrade(studentCourseId, usualGrade, examGrade, remark);
    }
    
    @Override
    @Transactional
    public boolean deleteGrade(Long studentCourseId) {
        try {
            StudentCourse studentCourse = studentCourseMapper.selectById(studentCourseId);
            if (studentCourse == null) {
                return false;
            }
            
            // 清空成绩信息
            studentCourse.setUsualGrade(null);
            studentCourse.setExamGrade(null);
            studentCourse.setFinalGrade(null);
            studentCourse.setGradeLevel(null);
            studentCourse.setRemark(null);
            
            // 将状态改回已选课
            studentCourse.setStatus("SELECTED");
            studentCourse.setUpdateTime(new Date());
            
            return studentCourseMapper.updateById(studentCourse) > 0;
        } catch (Exception e) {
            throw new RuntimeException("删除成绩失败：" + e.getMessage());
        }
    }
    
    @Override
    public Map<String, Object> calculateFinalGrade(BigDecimal usualGrade, BigDecimal examGrade) {
        Map<String, Object> result = new HashMap<>();
        
        // 如果平时成绩或考试成绩为空，无法计算总成绩
        if (usualGrade == null || examGrade == null) {
            result.put("finalGrade", null);
            result.put("gradeLevel", null);
            return result;
        }
        
        // 计算总成绩：平时成绩占40%，考试成绩占60%
        BigDecimal finalGrade = usualGrade.multiply(new BigDecimal("0.4"))
                                         .add(examGrade.multiply(new BigDecimal("0.6")))
                                         .setScale(2, RoundingMode.HALF_UP);
        
        // 根据总成绩计算等级
        String gradeLevel = calculateGradeLevel(finalGrade);
        
        result.put("finalGrade", finalGrade);
        result.put("gradeLevel", gradeLevel);
        
        return result;
    }
    
    /**
     * 根据分数计算等级
     */
    private String calculateGradeLevel(BigDecimal score) {
        if (score == null) {
            return null;
        }
        
        double scoreValue = score.doubleValue();
        
        if (scoreValue >= 95) {
            return "A+";
        } else if (scoreValue >= 90) {
            return "A";
        } else if (scoreValue >= 85) {
            return "A-";
        } else if (scoreValue >= 82) {
            return "B+";
        } else if (scoreValue >= 78) {
            return "B";
        } else if (scoreValue >= 75) {
            return "B-";
        } else if (scoreValue >= 72) {
            return "C+";
        } else if (scoreValue >= 68) {
            return "C";
        } else if (scoreValue >= 64) {
            return "C-";
        } else if (scoreValue >= 60) {
            return "D";
        } else {
            return "F";
        }
    }
}

